package com.hui.qiniucloud.service.impl;

import com.hui.qiniucloud.dto.*;
import com.hui.qiniucloud.entity.AICharacter;
import com.hui.qiniucloud.entity.ChatMessage;
import com.hui.qiniucloud.entity.ChatSession;
import com.hui.qiniucloud.mapper.ChatMessageMapper;
import com.hui.qiniucloud.mapper.ChatSessionMapper;
import com.hui.qiniucloud.service.IChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 聊天服务实现类
 */
@Slf4j
@Service
public class ChatServiceImpl implements IChatService {

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private DoubaoUniversalService doubaoUniversalService;

    @Autowired
    private CharacterService characterService;

    @Override
    @Transactional
    public ChatMessageResponse sendMessage(Long userId, ChatMessageRequest request) {
        Long sessionId = request.getSessionId();
        ChatSession session = null;

        // 如果没有会话ID，创建新会话
        if (sessionId == null) {
            session = createNewSession(userId, request);
            sessionId = session.getId();
        } else {
            // 验证会话是否属于当前用户
            session = chatSessionMapper.selectByIdAndUserId(sessionId, userId);
            if (session == null) {
                throw new RuntimeException("会话不存在或无权限访问");
            }
        }

        // 保存用户消息
        ChatMessage userMessage = new ChatMessage(sessionId, "user", request.getContent());
        chatMessageMapper.insert(userMessage);

        try {
            // 获取历史消息用于API调用
            List<Map<String, String>> chatHistory = chatMessageMapper.selectApiFormatBySessionId(sessionId);

            // 调用AI接口
            String aiResponse;
            if (StringUtils.hasText(request.getCharacterId())) {
                // 角色扮演模式
                AICharacter character = characterService.getCharacterById(request.getCharacterId());
                if (character == null) {
                    throw new RuntimeException("角色不存在");
                }
                aiResponse = doubaoUniversalService.chatWithCharacter(request.getContent(), character, chatHistory).block();
            } else {
                // 普通聊天模式
                aiResponse = doubaoUniversalService.chat(request.getContent(), null, chatHistory).block();
            }

            // 保存AI响应
            ChatMessage assistantMessage = new ChatMessage(sessionId, "assistant", aiResponse);
            chatMessageMapper.insert(assistantMessage);

            // 更新会话信息
            Integer messageCount = chatMessageMapper.countBySessionId(sessionId);
            chatSessionMapper.updateLastMessageAndCount(sessionId, request.getContent(), messageCount);

            // 构建响应
            ChatMessageResponse response = new ChatMessageResponse();
            response.setSessionId(sessionId);
            response.setSessionTitle(session.getTitle());
            response.setContent(aiResponse);
            response.setUserMessage(request.getContent());
            response.setTimestamp(LocalDateTime.now());

            // 设置角色信息
            if (StringUtils.hasText(request.getCharacterId())) {
                AICharacter character = characterService.getCharacterById(request.getCharacterId());
                if (character != null) {
                    ChatMessageResponse.CharacterInfo characterInfo = new ChatMessageResponse.CharacterInfo();
                    characterInfo.setId(character.getId());
                    characterInfo.setName(character.getName());
                    characterInfo.setDescription(character.getDescription());
                    response.setCharacter(characterInfo);
                }
            }

            log.info("用户 {} 发送消息成功，会话ID: {}", userId, sessionId);
            return response;

        } catch (Exception e) {
            log.error("AI接口调用失败: {}", e.getMessage(), e);
            throw new RuntimeException("AI服务暂时不可用，请稍后重试");
        }
    }

    @Override
    public List<ChatSessionResponse> getUserSessions(Long userId) {
        List<ChatSession> sessions = chatSessionMapper.selectByUserId(userId);
        return sessions.stream()
                .map(this::convertToSessionResponse)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatSessionResponse> getUserSessionsByCharacter(Long userId, String characterId) {
        List<ChatSession> sessions = chatSessionMapper.selectByUserIdAndCharacterId(userId, characterId);
        return sessions.stream()
                .map(this::convertToSessionResponse)
                .collect(Collectors.toList());
    }

    @Override
    public ChatHistoryResponse getChatHistory(Long userId, Long sessionId) {
        // 验证会话权限
        ChatSession session = chatSessionMapper.selectByIdAndUserId(sessionId, userId);
        if (session == null) {
            throw new RuntimeException("会话不存在或无权限访问");
        }

        // 获取消息列表
        List<ChatMessage> messages = chatMessageMapper.selectBySessionId(sessionId);

        // 构建响应
        ChatHistoryResponse response = new ChatHistoryResponse();

        // 设置会话信息
        ChatHistoryResponse.SessionInfo sessionInfo = new ChatHistoryResponse.SessionInfo();
        sessionInfo.setId(session.getId());
        sessionInfo.setTitle(session.getTitle());

        // 设置角色信息
        if (StringUtils.hasText(session.getCharacterId())) {
            AICharacter character = characterService.getCharacterById(session.getCharacterId());
            if (character != null) {
                ChatHistoryResponse.CharacterInfo characterInfo = new ChatHistoryResponse.CharacterInfo();
                characterInfo.setId(character.getId());
                characterInfo.setName(character.getName());
                characterInfo.setAvatar(character.getAvatar());
                sessionInfo.setCharacter(characterInfo);
            }
        }

        response.setSession(sessionInfo);

        // 设置消息列表（过滤掉system消息）
        List<ChatHistoryResponse.MessageInfo> messageInfos = messages.stream()
                .filter(msg -> !"system".equals(msg.getRole()))
                .map(msg -> {
                    ChatHistoryResponse.MessageInfo messageInfo = new ChatHistoryResponse.MessageInfo();
                    messageInfo.setId(msg.getId());
                    messageInfo.setRole(msg.getRole());
                    messageInfo.setContent(msg.getContent());
                    messageInfo.setCreatedTime(msg.getCreatedTime());
                    return messageInfo;
                })
                .collect(Collectors.toList());

        response.setMessages(messageInfos);

        return response;
    }

    @Override
    @Transactional
    public void deleteSession(Long userId, Long sessionId) {
        // 验证会话权限
        ChatSession session = chatSessionMapper.selectByIdAndUserId(sessionId, userId);
        if (session == null) {
            throw new RuntimeException("会话不存在或无权限访问");
        }

        // 删除会话和相关消息
        chatSessionMapper.deleteById(sessionId);
        chatMessageMapper.deleteBySessionId(sessionId);

        log.info("用户 {} 删除会话 {} 成功", userId, sessionId);
    }

    @Override
    public void updateSessionTitle(Long userId, Long sessionId, String title) {
        int updated = chatSessionMapper.updateTitleByIdAndUserId(sessionId, userId, title);
        if (updated == 0) {
            throw new RuntimeException("会话不存在或无权限访问");
        }

        log.info("用户 {} 更新会话 {} 标题成功: {}", userId, sessionId, title);
    }

    @Override
    public List<ChatSessionResponse> searchSessions(Long userId, String keyword) {
        List<ChatSession> sessions;
        if (StringUtils.hasText(keyword)) {
            sessions = chatSessionMapper.searchByUserIdAndKeyword(userId, keyword);
        } else {
            sessions = chatSessionMapper.selectByUserId(userId);
        }

        return sessions.stream()
                .map(this::convertToSessionResponse)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void clearAllSessions(Long userId) {
        List<ChatSession> sessions = chatSessionMapper.selectByUserId(userId);

        for (ChatSession session : sessions) {
            chatSessionMapper.deleteById(session.getId());
            chatMessageMapper.deleteBySessionId(session.getId());
        }

        log.info("用户 {} 清空所有聊天记录成功，共删除 {} 个会话", userId, sessions.size());
    }

    /**
     * 创建新会话
     */
    private ChatSession createNewSession(Long userId, ChatMessageRequest request) {
        String title = StringUtils.hasText(request.getSessionTitle()) ? request.getSessionTitle() : "新对话";
        ChatSession session = new ChatSession(userId, request.getCharacterId(), title);
        chatSessionMapper.insert(session);

        log.info("用户 {} 创建新会话成功，会话ID: {}", userId, session.getId());
        return session;
    }

    /**
     * 转换为会话响应DTO
     */
    private ChatSessionResponse convertToSessionResponse(ChatSession session) {
        ChatSessionResponse response = new ChatSessionResponse();
        BeanUtils.copyProperties(session, response);

        // 设置角色信息
        if (StringUtils.hasText(session.getCharacterId())) {
            AICharacter character = characterService.getCharacterById(session.getCharacterId());
            if (character != null) {
                ChatSessionResponse.CharacterInfo characterInfo = new ChatSessionResponse.CharacterInfo();
                characterInfo.setId(character.getId());
                characterInfo.setName(character.getName());
                characterInfo.setAvatar(character.getAvatar());
                response.setCharacter(characterInfo);
            }
        }

        return response;
    }
}